package org.linlinjava.litemall.admin.web;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.core.consts.BrokerageTypeConsts;
import org.linlinjava.litemall.core.qcode.QCodeService;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.LitemallUserAccount;
import org.linlinjava.litemall.db.domain.LitemallUserVo;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/admin/user")
@Validated
public class AdminUserController {
    private final Log logger = LogFactory.getLog(AdminUserController.class);

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private QCodeService qCodeService;
    
    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String username, String mobile, Integer brokerage,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<LitemallUserVo> userList = userService.queryUserPage(username, mobile, brokerage, page, limit, sort, order);
        return ResponseUtil.okList(userList);
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("admin:user:read")
    @RequiresPermissionsDesc(menu = { "用户管理", "会员管理" }, button = "代理详情")
    @GetMapping("/detailApprove")
    public Object detailApprove(@NotNull Integer id) {
        logger.info(String.format("【请求开始】用户管理->会员管理->代理详情,请求参数:id:[%d]", id));

        LitemallUserAccount dbAccount = userService.detailApproveByUserId(id);
        if (dbAccount == null) {
            logger.error("用户管理->会员管理->代理详情 错误：代理账号信息不存在");
            ResponseUtil.badArgumentValue();
        }
        logger.info(String.format("【请求结束】用户管理->会员管理->代理详情:响应结果:[%s]", JSONObject.toJSONString(dbAccount)));
        return ResponseUtil.ok(dbAccount);
    }

    @RequiresPermissions("admin:user:approveAgency")
    @RequiresPermissionsDesc(menu = { "用户管理", "会员管理" }, button = "代理审批")
    @PostMapping("/approveAgency")
    public Object approveAgency(@RequestBody String body) {
        logger.info(String.format("【请求开始】用户管理->会员管理->代理审批,请求参数:[%s]",body));

        Integer userId = JacksonUtil.parseInteger(body, "userId");
        Integer settlementRate = JacksonUtil.parseInteger(body, "settlementRate");

        if (userId == null || settlementRate == null || settlementRate.intValue() <= 0 ){
            return ResponseUtil.badArgument();
        }
        try {
            /*
             * 生成代理用户独有分享的二维码需要小程序已经上线，所以未上线小程序这里调用会异常
             * 建议通过后台参数控制，因为定制用户对这里的特殊性要求，本程序暂不做调整
             */
            String shareUrl = qCodeService.createShareUserImage(userId);

            userService.approveAgency(userId,settlementRate,shareUrl, BrokerageTypeConsts.BROKERAGE);
        }catch (Exception e) {
            logger.error(String.format("用户管理->会员管理->代理审批 出错：[%s]",e.getMessage()));
            e.printStackTrace();
        }

        logger.info("【请求结束】用户管理->会员管理->代理审批:响应结果:成功!");
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:user:cancelAgency")
    @RequiresPermissionsDesc(menu = { "用户管理", "会员管理" }, button = "取消代理")
    @PostMapping("/cancelAgency")
    public Object cancelAgency(@RequestBody String body) {
        logger.info(String.format("【请求开始】用户管理->会员管理->取消代理,请求参数:[%s]",body));

        Integer userId = JacksonUtil.parseInteger(body, "userId");
        try {
            userService.cancelAgency(userId, BrokerageTypeConsts.NOT_BROKERAGE);
        }catch (Exception e) {
            logger.error(String.format("用户管理->会员管理->取消代理 出错：[%s]",e.getMessage()));
            e.printStackTrace();
        }

        logger.info("【请求结束】用户管理->会员管理->取消代理:响应结果:成功!");
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:user:updateUser")
    @RequiresPermissionsDesc(menu = { "用户管理", "会员管理" }, button = "更新用户")
    @PostMapping("/updateUser")
    public Object updateUser(@RequestBody LitemallUser user) {
        logger.info(String.format("【请求开始】用户管理->会员管理->更新用户,请求参数:[%s]", JSONObject.toJSON(user)));
        Object error = validate(user);
        if (error != null) {
            return error;
        }
        if (userService.updateById(user) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        logger.info("【请求结束】用户管理->会员管理->更新用户:响应结果:成功!");
        return ResponseUtil.ok();
    }


    private Object validate(LitemallUser user) {
        String name = user.getUsername();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }

        String desc = user.getNickname();
        if (StringUtils.isEmpty(desc)) {
            return ResponseUtil.badArgument();
        }

        Byte status = user.getStatus();
        if (status == null) {
            return ResponseUtil.badArgument();
        }

        String mobile = user.getMobile();
        if (mobile == null) {
            return ResponseUtil.badArgument();
        }
        return null;
    }
}
